﻿using System;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.WebProvider;
using ZBJF.Warranty.Common.Enums.InsuranceOrder;
using ZBJF.Warranty.Common.Enums.InsuranceProducts;
using ZBJF.Warranty.Model.ViewModel.InsuranceProducts;
using ZBJF.Warranty.Common.Enums.Data;
using ZBJF.Warranty.Common.Enums.InsuranceOrder.Data;
using ZBJF.Warranty.Model;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Text;
using System.Transactions;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model.ViewModel.AuditConfig;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Model.ViewModel.InfoCollect;
using ZBJF.Warranty.Common.Enums.InfoCollect;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class InsuranceProductsController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult Index(InsuranceProductsModel model)
        {
            var total = 0; //.Include(o => o.InsuranceProductScreenSPs)
            var list = ServiceFactory.InsuranceProductsServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.ProductName,
                o.InsuranceProductNo,
                o.Coverage,
                o.PolicyPeriodYear,
                o.PolicyPeriodMonth,
                o.PolicyPeriodDay,
                o.IsAvailable,
                o.LastModifyTime
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #region 查看保险产品详情
        public ActionResult Detail(int id)
        {
            var order = ServiceFactory.InsuranceProductsServiceInstance.LoadByID(id);
            return View(order);
        }
        #endregion

        #region 添加保险产品详情
        /// <summary>
        ///添加或修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(int id)
        {
            var insuranceProduct = ServiceFactory.InsuranceProductsServiceInstance.LoadByID(id);
            return View(insuranceProduct);
        }

        [HttpPost]
        public JsonResult UpdateInsuranceProducts(int id, bool isAvailable)
        {
            var responseResult = new ResponseResult { OpreateType = OpreateType.Update };

            var entity = ServiceFactory.InsuranceProductsServiceInstance.LoadByID(id);
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                entity.LastModifyTime = DateTime.Now;
                entity.LastModifyBy = CurrentUser.UserAccount;
                responseResult.Success = ServiceFactory.InsuranceProductsServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SaveInsuranceProducts(InsuranceProducts model, int[] AccessoriesTypeID, int[] insuranceWarrantyMaintenanceTypeId, int[] availableScreenType, string availableModelType)
        {
            var responseResult = new ResponseResult { OpreateType = OpreateType.Save };
            var serv = ServiceFactory.InsuranceProductsServiceInstance;
            //可承保型号
            List<int> availableModel = new List<int>();
            if (!string.IsNullOrWhiteSpace(availableModelType))
            {
                availableModel = availableModelType.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries).Select(Int32.Parse).ToList();
            }

            if (model.ID > 0)//修改
            {
                responseResult.Success = UpdateInsuranceProducts(model, AccessoriesTypeID, insuranceWarrantyMaintenanceTypeId, availableScreenType, availableModel);
            }
            else//新增
            {
                //判断该产品名称是否存在
                if (serv.IsExist(model.ProductName))
                {
                    responseResult.Message = "该产品名称已经存在,请修改后提交！";
                }
                else
                {
                    responseResult.Success = AddInsuranceProducts(model, AccessoriesTypeID, insuranceWarrantyMaintenanceTypeId, availableScreenType, availableModel);
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction(responseResult.Success ? "Index" : "Edit", new { id = model.ID });
        }

        private bool UpdateInsuranceProducts(InsuranceProducts model, int[] AccessoriesTypeID, int[] insuranceWarrantyMaintenanceTypeId, int[] availableScreenType, List<int> availableModelType)
        {
            //var ipSvc = ServiceFactory.InsuranceProductsServiceInstance;
            //var insuranceProducts = ipSvc.LoadByID(model.ID);
            //if (insuranceProducts == null)
            //{
            //    return false;
            //}
            //insuranceProducts.LastModifyBy = CurrentUser.UserAccount;
            //insuranceProducts.LastModifyTime = DateTime.Now;
            //insuranceProducts.ProductName = model.ProductName;//产品名称
            //insuranceProducts.Coverage = model.Coverage;//保额
            //insuranceProducts.InsuranceDevice = model.InsuranceDevice;//被保险设备
            //insuranceProducts.InsuranceDeviceType = model.InsuranceDeviceType;//被保险设备类型
            //insuranceProducts.WaitDays = model.WaitDays;//生效等待期
            //insuranceProducts.NewMachineInsuranceTimeLimit = model.NewMachineInsuranceTimeLimit;//新机投保期限
            //insuranceProducts.PolicyPeriod = model.PolicyPeriod;//保险期限
            //insuranceProducts.PolicyPeriodUnit = model.PolicyPeriodUnit;//保险期限
            //insuranceProducts.InsuranceProductCategory = model.InsuranceProductCategory;//产品类型 
            //insuranceProducts.IsAvailable = model.IsAvailable;
            //insuranceProducts.ProductAmountFrom = model.ProductAmountFrom;//可保价格区间_开始
            //insuranceProducts.ProductAmountTo = model.ProductAmountTo;//可保价格区间_结尾
            //insuranceProducts.UseModelTypeOption = model.UseModelTypeOption;//是否开启可保机型
            //insuranceProducts.UsePriceOption = model.UsePriceOption;//是否开启价格区间
            //insuranceProducts.UseScreenTypeOption = model.UseScreenTypeOption;//是否开启可保屏幕类型
            //using (TransactionScope sc = new TransactionScope())
            //{
            //    try
            //    {
            //        if (!ipSvc.UpdateEntities(insuranceProducts))
            //        {
            //            sc.Dispose();
            //            return false;
            //        }

            //        var spsSvc = ServiceFactory.InsuranceProductScreenSPsServiceInstance;
            //        var entitySpList = spsSvc.GetInsuranceProductScreenSPsAll(insuranceProducts.ID).ToList();
            //        if (entitySpList.Any())
            //        {
            //            for (int i = 0; i < entitySpList.Count(); i++)
            //            {
            //                var insuranceProductScreenSPs = entitySpList[i];
            //                if (!spsSvc.DeleteEntities(insuranceProductScreenSPs))
            //                {
            //                    sc.Dispose();
            //                    return false;
            //                }
            //            }
            //        }
            //        InsuranceProductScreenSPs ipssList = new InsuranceProductScreenSPs();
            //        for (int j = 0; j < AccessoriesTypeID.Length; j++)
            //        {
            //            ipssList.InsuranceProductId = insuranceProducts.ID;
            //            ipssList.AccessoriesTypeID = AccessoriesTypeID[j];
            //            if (spsSvc.AddEntities(ipssList).ID < 1)
            //            {
            //                sc.Dispose();
            //                return false;
            //            }
            //        }
            //        var servipwmtsi = ServiceFactory.InsuranceProductWarrantyMaintenanceTypesServiceInstance;
            //        var entityipwmtsList = servipwmtsi.GetInsuranceProductWarrantyMaintenanceTypesAll(insuranceProducts.ID).ToList();
            //        if (entityipwmtsList.Any())
            //        {
            //            for (int i = 0; i < entityipwmtsList.Count(); i++)
            //            {
            //                var insuranceProductWarrantyMaintenanceTypes = entityipwmtsList[i];
            //                if (!servipwmtsi.DeleteEntities(insuranceProductWarrantyMaintenanceTypes))
            //                {
            //                    sc.Dispose();
            //                    return false;
            //                }
            //            }
            //        }
            //        InsuranceProductWarrantyMaintenanceTypes ipwmList = new InsuranceProductWarrantyMaintenanceTypes();
            //        for (int j = 0; j < insuranceWarrantyMaintenanceTypeId.Length; j++)
            //        {
            //            ipwmList.InsuranceProductId = insuranceProducts.ID;
            //            ipwmList.InsuranceWarrantyMaintenanceTypeId = insuranceWarrantyMaintenanceTypeId[j];
            //            if (servipwmtsi.AddEntities(ipwmList).ID < 1)
            //            {
            //                sc.Dispose();
            //                return false;
            //            }
            //        }
            //        #region 更新可保型号——先删后增
            //        var insuranceProductsAvailableModelTypeServiceInstance = ServiceFactory.InsuranceProductsAvailableModelTypeServiceInstance;
            //        bool re = insuranceProductsAvailableModelTypeServiceInstance.DeleteInsuranceProductsAvailableModelType(insuranceProducts.ID);
            //        if (model.UseModelTypeOption && availableModelType != null && availableModelType.Count() > 0)
            //        {
            //            InsuranceProductsAvailableModelType modeltype = new InsuranceProductsAvailableModelType();
            //            modeltype.InsuranceProductsID = insuranceProducts.ID;
            //            foreach (long item in availableModelType)
            //            {
            //                modeltype.ModelID = item;
            //                //添加失败，回滚事务
            //                if (insuranceProductsAvailableModelTypeServiceInstance.AddEntities(modeltype).ID < 1)
            //                {
            //                    sc.Dispose();
            //                    return false;
            //                }
            //            }
            //        }
            //        #endregion

            //        #region 保存此产品所适用的屏幕类型——先删后增
            //        var insuranceProductsAvailableScreenTypeServiceInstance = ServiceFactory.InsuranceProductsAvailableScreenTypeServiceInstance;
            //        bool reScreen = insuranceProductsAvailableScreenTypeServiceInstance.DeleteInsuranceProductsAvailableScreenType(insuranceProducts.ID);
            //        if (model.UseScreenTypeOption && availableScreenType != null && availableScreenType.Count() > 0)
            //        {
            //            InsuranceProductsAvailableScreenType modeltype = new InsuranceProductsAvailableScreenType();
            //            modeltype.InsuranceProductsID = insuranceProducts.ID;
            //            foreach (byte item in availableScreenType)
            //            {
            //                modeltype.ScreenTypeCode = item;
            //                //添加失败，回滚事务
            //                if (insuranceProductsAvailableScreenTypeServiceInstance.AddEntities(modeltype).ID < 1)
            //                {
            //                    sc.Dispose();
            //                    return false;
            //                }
            //            }
            //        }
            //        #endregion
            //        sc.Complete();

            //    }
            //    catch (Exception ex)
            //    {
            //        LogHelper.WriteLog("更新保险产品异常" + ex.ToString(), LogType.error);
            //        sc.Dispose();
            //        return false;
            //    }
            //}
            return true;
        }

        private bool AddInsuranceProducts(InsuranceProducts model, int[] AccessoriesTypeID, int[] insuranceWarrantyMaintenanceTypeId, int[] availableScreenType, List<int> availableModelType)
        {
            //var serv = ServiceFactory.InsuranceProductsServiceInstance;
            //model.CreateTime = DateTime.Now;
            //model.CreateBy = CurrentUser.UserAccount;
            //model.LastModifyBy = CurrentUser.UserAccount;
            //model.LastModifyTime = DateTime.Now;
            //model.IsAvailable = true;
            //model.InsuranceProductNo = "SP" + CommonMethod.GetTimeStamp();
            //using (TransactionScope sc = new TransactionScope())
            //{
            //    try
            //    {
            //        var entity = serv.AddEntities(model);
            //        if (entity.ID < 1)
            //        {
            //            sc.Dispose();
            //            return false;
            //        }

            //        if (AccessoriesTypeID.Length > 0)
            //        {
            //            var servs = ServiceFactory.InsuranceProductScreenSPsServiceInstance;

            //            var ipss = new InsuranceProductScreenSPs();
            //            ipss.InsuranceProductId = entity.ID;
            //            foreach (var spTypeId in AccessoriesTypeID)
            //            {
            //                ipss.AccessoriesTypeID = spTypeId;
            //                //添加失败，回滚事务
            //                if (servs.AddEntities(ipss).ID < 1)
            //                {
            //                    sc.Dispose();
            //                    return false;
            //                }
            //            }
            //        }
            //        if (insuranceWarrantyMaintenanceTypeId.Length > 0)
            //        {
            //            var servss = ServiceFactory.InsuranceProductWarrantyMaintenanceTypesServiceInstance;
            //            var ipwmt = new InsuranceProductWarrantyMaintenanceTypes();
            //            ipwmt.InsuranceProductId = entity.ID;
            //            foreach (var iwmTypeId in insuranceWarrantyMaintenanceTypeId)
            //            {
            //                ipwmt.InsuranceWarrantyMaintenanceTypeId = iwmTypeId;
            //                //添加失败，回滚事务
            //                if (servss.AddEntities(ipwmt).ID < 1)
            //                {
            //                    sc.Dispose();
            //                    return false;
            //                }
            //            }
            //        }
            //        #region 保存此产品所适用的型号
            //        if (model.UseModelTypeOption && availableModelType != null && availableModelType.Count() > 0)
            //        {
            //            var insuranceProductsAvailableModelTypeServiceInstance = ServiceFactory.InsuranceProductsAvailableModelTypeServiceInstance;
            //            InsuranceProductsAvailableModelType modeltype = new InsuranceProductsAvailableModelType();
            //            modeltype.InsuranceProductsID = entity.ID;
            //            foreach (long item in availableModelType)
            //            {
            //                modeltype.ModelID = item;
            //                //添加失败，回滚事务
            //                if (insuranceProductsAvailableModelTypeServiceInstance.AddEntities(modeltype).ID < 1)
            //                {
            //                    sc.Dispose();
            //                    return false;
            //                }
            //            }
            //        }
            //        #endregion
            //        #region 保存此产品所适用的屏幕类型
            //        if (model.UseScreenTypeOption && availableScreenType != null && availableScreenType.Count() > 0)
            //        {
            //            var insuranceProductsAvailableScreenTypeServiceInstance = ServiceFactory.InsuranceProductsAvailableScreenTypeServiceInstance;
            //            InsuranceProductsAvailableScreenType modeltype = new InsuranceProductsAvailableScreenType();
            //            modeltype.InsuranceProductsID = entity.ID;
            //            foreach (byte item in availableScreenType)
            //            {
            //                modeltype.ScreenTypeCode = item;
            //                //添加失败，回滚事务
            //                if (insuranceProductsAvailableScreenTypeServiceInstance.AddEntities(modeltype).ID < 1)
            //                {
            //                    sc.Dispose();
            //                    return false;
            //                }
            //            }
            //        }
            //        #endregion
            //        sc.Complete();
            //    }
            //    catch (Exception ex)
            //    {
            //        sc.Dispose();
            //        LogHelper.WriteLog("保存保险产品信息异常：" + ex.ToString(), LogType.error);
            //        return false;
            //    }
            //}
            return true;
        }
        #endregion

        #region 添加基础保险产品_新

        public ActionResult AddInsuranceProductsBase(int id)
        {
            var insuranceProduct = ServiceFactory.InsuranceProductsServiceInstance.LoadEntities(t => t.ID == id).FirstOrDefault();
            return View(insuranceProduct);
        }

        #region 获取基础保险产品下的服务项目列表 + JsonResult GetProductServiceProjectList(int id)
        /// <summary>
        /// 获取基础保险产品下的服务项目列表
        /// </summary>
        /// <param name="id">基础保险产品ID</param>
        /// <returns></returns>
        public JsonResult GetProductServiceProjectList(int id)
        {
            if(id<1)
                return Json(new { Result = false, Message = "参数错误" });

            //手机维修服务
           List<CellPhoneServiceProjectModel> cellPhoneServiceProject = ServiceFactory.CellPhoneServiceProjectServiceInstance.GetProductCellPhoneServiceProjectList(id);
            //家电清洗服务

            //家电维修服务

            return Json(new { Result = true, Message = "获取成功" ,Data=new { CellPhoneServiceProject= cellPhoneServiceProject } }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 保存基础产品信息 + ActionResult SaveInsuranceProductsBase()
        [HttpPost]
        public JsonResult SaveInsuranceProductsBase(InsuranceProductsBase param)
        {
            if (param == null)
            {
                return Json(new { Result = false, Message = "参数错误" });
            }
            //新增
            if (param.ID < 1)
            {
                param.CreateTime = DateTime.Now;
                param.CreateBy = CurrentUser.UserAccount;
                param.LastModifyBy = CurrentUser.UserAccount;
                param.LastModifyTime = DateTime.Now;
                param.IsAvailable = true;
                bool re = ServiceFactory.InsuranceProductsServiceInstance.AddInsuranceProductsBase(param);
                if (re)
                    return Json(new { Result = true, Message = "添加成功" });
                else
                    return Json(new { Result = false, Message = "添加失败" });
            }
            //修改
            else
            {
                param.LastModifyBy = CurrentUser.UserAccount;
                param.LastModifyTime = DateTime.Now;
                param.IsAvailable = true;
                bool re = ServiceFactory.InsuranceProductsServiceInstance.UpdateInsuranceProductsBase(param);
                if (re)
                    return Json(new { Result = true, Message = "修改成功" });
                else
                    return Json(new { Result = false, Message = "修改失败" });
            }
        }
        #endregion

        #region 基础产品——手机维修服务int InsuranceProductsId

        public ActionResult CellPhoneRepairService()
        {
            //获取所有的审核项目
            ViewBag.allAuditModel = GetAuditModel();

            //获取所有的资料收集项目
            ViewBag.allInfoCollectModel = GetInfoCollectModel();

            return View();
        }

        #region 获取所有的审核项目 + List<AuditProjectConfigurationSelectModel> GetAuditModel()
        private List<AuditProjectConfigurationSelectModel> GetAuditModel()
        {
            //获取所有的审核项目
            var allAuditModel = ServiceFactory.AuditProjectConfigurationServiceInstance.GetAllAuditModel();
            SelectList select = ConvertToSelector.Instance.EnumTypeConvertToSelectList(typeof(AuditProjectTypeEnum), 0, false);
            if (allAuditModel == null)
                allAuditModel = new List<AuditProjectConfigurationSelectModel>();
            //把审核项目类别加进去。 形成父子级关系
            foreach (var item in select)
            {
                allAuditModel.Add(new AuditProjectConfigurationSelectModel()
                {
                    ID = -int.Parse(item.Value), //把项目类型转成负数，避免与审核项目ID重复
                    ProjectName = item.Text,
                    AuditProjectWithType = 0
                });
            }
            return allAuditModel;
        }
        #endregion

        #region 获取所有的资料收集项目 + List<InfoCollectSelectModel> GetInfoCollectModel()
        private List<InfoCollectSelectModel> GetInfoCollectModel()
        {
            //获取所有的审核项目
            var allInfoCollectModel = (from a in ServiceFactory.CollectTypeCollectItemMappingsServiceInstance.LoadEntities(t => true).AsNoTracking()
                                       join b in ServiceFactory.InsuranceProductsInfoCollectItemServiceInstance.LoadEntities(t => true).AsNoTracking() on a.CollectItemID equals b.ID into temp
                                       from c in temp.DefaultIfEmpty()
                                       join d in ServiceFactory.InsuranceProductsInfoCollectCategoryServiceInstance.LoadEntities(t => true).AsNoTracking() on c.InfoCollectCategoryID equals d.ID into temp1
                                       from e in temp1.DefaultIfEmpty()
                                       select new
                                       {
                                           InfoCollectName = c.InfoCollectItemName,
                                           ID = a.ID,
                                           CollectWithType = a.CollectWithType,
                                           InfoCollectCategoryName = e.InfoCollectCategoryName
                                       }).ToList().Select(t => new InfoCollectSelectModel
                                       {
                                           ID = t.ID,
                                           InfoCollectName = t.InfoCollectName,
                                           CollectWithType = Convert.ToInt32(-t.CollectWithType), //把项目类型转成负数，避免与收集项目ID重复
                                           InfoCollectCategoryName = t.InfoCollectCategoryName
                                       }).ToList();
            SelectList select = ConvertToSelector.Instance.EnumTypeConvertToSelectList(typeof(CollectWithType), 0, false);
            if (allInfoCollectModel == null)
                allInfoCollectModel = new List<InfoCollectSelectModel>();
            //把审核项目类别加进去。 形成父子级关系
            foreach (var item in select)
            {
                allInfoCollectModel.Add(new InfoCollectSelectModel()
                {
                    ID = -int.Parse(item.Value), //把项目类型转成负数，避免与收集项目ID重复
                    InfoCollectName = item.Text,
                    CollectWithType = 0
                });
            }
            return allInfoCollectModel;
        }
        #endregion

        #region 选择审核项目 + ActionResult AuditProjectConfigurationSelect(List<AuditProjectConfigurationSelectModel> listPage, int pid = 0, int layer = 0)
        /// <summary>
        /// 选择审核项目
        /// </summary>
        /// <param name="listPage">数据集合</param>
        /// <param name="pid">父级ID</param>
        /// <param name="layer">布局（距离左侧多少像素）</param>
        /// <returns></returns>
        public ActionResult AuditProjectConfigurationSelect(List<AuditProjectConfigurationSelectModel> listPage, int pid = 0, int layer = 0)
        {
            ViewBag.Pid = pid;
            ViewBag.Layer = layer;
            return View(listPage);
        }
        #endregion 

        #region 选择信息收集项目 + ActionResult InfoCollectSelect(List<InfoCollectSelectModel> listPage, int pid = 0, int layer = 0)
        /// <summary>
        /// 选择信息收集项目
        /// </summary>
        /// <param name="listPage">数据集合</param>
        /// <param name="pid">父级ID</param>
        /// <param name="layer">布局（距离左侧多少像素）</param>
        /// <returns></returns>
        public ActionResult InfoCollectSelect(List<InfoCollectSelectModel> listPage, int pid = 0, int layer = 0)
        {
            ViewBag.Pid = pid;
            ViewBag.Layer = layer;
            return View(listPage);
        }
        #endregion 

        #endregion

        #endregion

        #region 导出保险产品详情
        /// <summary>  
        ///
        /// </summary>  
        /// <returns></returns>  
        public ActionResult ExportInsuranceDetails(string content)
        {
            InsuranceProductsModel model = JsonConvert.DeserializeObject<InsuranceProductsModel>(content);
            var total = 0;
            model.iDisplayStart = 0;
            model.iDisplayLength = int.MaxValue;
            model.iSorts = "ID desc";
            var list = ServiceFactory.InsuranceProductsServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.ProductName,
                o.InsuranceProductNo,
                o.Coverage,
                o.PolicyPeriodYear,
                o.PolicyPeriodMonth,
                o.PolicyPeriodDay,
                o.IsAvailable,
                o.LastModifyTime
            });
            var dt = ListToDatatableHelper.ToDataTable(list.ToList());
            dt.TableName = "List";
            List<DataTable> dataSoure = new List<DataTable> { dt };
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string execlPath = Server.MapPath("\\").Trim('\\') + "\\DownLoad\\Template\\InsuranceProductList.xlsx";
            string fileName = "InsuranceProductList-(" + DateTime.Now.ToString("yyyyMMdd") + ")";
            ExcelHelper.ExportToExcel(execlPath, dic, dataSoure, fileName);
            return Json(new object { });
        }
        #endregion
        
        #region 判断产品名称是否存在

        public bool IsExistInsuranceProducts(string productName, long id = 0)
        {
            return ServiceFactory.InsuranceProductsServiceInstance.IsExist(productName, id);
        }

        #endregion
    }
}